
import sys, os
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))

import pandas as pd
import matplotlib.pyplot as plt
from AppAnalysis import get_app_df, get_subscription_event_df, get_inner_purchase_df, ColumnName as cn
from datetime import datetime
from AppStoreConnect.Product import AppProduct
from AppStoreConnect import Courntries
from AppDB import AppDB
from enum import Enum




def get_subscriptions_sales_analysis(sub1_id:str, sub2_id:str, start_date:datetime, end_date:datetime, parent_app_df:pd.DataFrame=None):
    
    sub1_df = get_inner_purchase_df(inner_purchase_apple_id=sub1_id, start_date=start_date, end_date=end_date, parent_app_df=parent_app_df)
    
    sub2_df = get_inner_purchase_df(inner_purchase_apple_id=sub2_id, start_date=start_date, end_date=end_date, parent_app_df=parent_app_df)
    
    df = sub1_df.merge(sub2_df, left_index=True, right_index=True, how='outer', suffixes=('_sub1', '_sub2'))

    return df


def get_Hearty_sales_analysis_df(start_date:datetime, end_date:datetime):
    
    app_df = get_app_df(app_apple_id=AppProduct.Hearty, start_date=start_date, end_date=end_date)
    print("App_df DataFrame. Country as index. Count: ", app_df.shape[0])
    
    premium_df = get_inner_purchase_df(inner_purchase_apple_id=AppProduct.Hearty_Premium_Version, start_date=start_date, end_date=end_date, parent_app_df=app_df)
    print("Premium_df DataFrame. Country as index. Count: ", premium_df.shape[0])
    
    subscription_df = get_subscriptions_sales_analysis(sub1_id=AppProduct.Sub_Hearty_1_Month, sub2_id=AppProduct.Sub_Hearty_1_Year, start_date=start_date, end_date=end_date, parent_app_df=app_df)

    df = app_df.merge(premium_df, left_index=True, right_index=True, how='outer')
        
    df = df.merge(subscription_df, left_index=True, right_index=True, how='outer')
    df.fillna(0, inplace=True)
    
    df[cn.total_proceeds_usd.value] = df[cn.proceeds_usd.value] + df[cn.proceeds_usd.value + '_sub1'] + df[cn.proceeds_usd.value + '_sub2']
    df[cn.general_preceeds_per_download_usd.value] = df[cn.total_proceeds_usd.value] / df[cn.downloads.value]
    df[cn.general_purchase_rate.value] = (df[cn.purchase_count.value] + df[cn.purchase_count.value + '_sub1'] + df[cn.purchase_count.value + '_sub2']) / df[cn.downloads.value]
    
    cols = list(df.columns)
    #将cols中列名为cn.total_proceeds_usd.value的列挪到第二个
    cols.insert(1, cols.pop(cols.index(cn.total_proceeds_usd.value)))
    #将cols中列名为cn.general_preceeds_per_download_usd.value的列挪到第三个
    cols.insert(2, cols.pop(cols.index(cn.general_preceeds_per_download_usd.value)))
    #将cols中列名为cn.general_purchase_rate.value的列挪到第4个
    cols.insert(3, cols.pop(cols.index(cn.general_purchase_rate.value)))
    
    df = df[cols]
    
    return df

if __name__ == "__main__":
    pass

    # period 1
    start_date_1 = datetime(2024, 4, 18)
    end_date_1 = datetime(2024, 4, 22)
    
    # period 2
    start_date_2 = datetime(2024, 4, 23)
    end_date_2 = datetime(2024, 5, 12)
    
    df1 = get_Hearty_sales_analysis_df(start_date=start_date_1, end_date=end_date_1)
    df2 = get_Hearty_sales_analysis_df(start_date=start_date_2, end_date=end_date_2)
    
    df = df1.merge(df2, left_index=True, right_index=True, how='outer', suffixes=('_P1', '_P2'))
    
    # 插入一列到第二列，根据country_code获取国家名称， 仍然将country_code作为index
    df['国家'] = df.index.map(lambda x: Courntries.get_country_name_from_alpha3Code(x) if x is not None else None)
    # 将'国家'列移到第一列
    cols = list(df.columns)
    cols = [cols[-1]] + cols[:-1]
    df = df[cols]
    
    # 将df导出到xlsx文件
    file_name = f'reports/Hearty_{start_date_1.strftime("%m-%d")}_to_{end_date_1.strftime("%m-%d")}_vs_{start_date_2.strftime("%m-%d")}_to_{end_date_2.strftime("%m-%d")}.xlsx'
    # 先删除文件
    if os.path.exists(file_name):
        os.remove(file_name)
    
    df.to_excel(file_name)
    print(f"Exported to {file_name}")
    